//package cn.com.connected.common.aop;
//
//import cn.com.connected.base.annotations.RateLimiter;
//import com.github.benmanes.caffeine.cache.Caffeine;
//import io.github.bucket4j.Bandwidth;
//import io.github.bucket4j.Bucket;
//import io.github.bucket4j.BucketConfiguration;
//import io.github.bucket4j.caffeine.CaffeineProxyManager;
//import io.github.bucket4j.distributed.proxy.ProxyManager;
//import io.github.bucket4j.distributed.remote.RemoteBucketState;
//import lombok.NonNull;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.stereotype.Component;
//import org.springframework.web.method.HandlerMethod;
//import org.springframework.web.servlet.HandlerInterceptor;
//
//import javax.servlet.http.HttpServletRequest;
//import javax.servlet.http.HttpServletResponse;
//import java.time.Duration;
//import java.util.concurrent.TimeUnit;
//
//@Slf4j
//@Component
//public class RateLimiterHandlerInterceptor implements HandlerInterceptor {
//    private final ProxyManager<String> proxyManager;
//
//    public RateLimiterHandlerInterceptor() {
//        Caffeine<String, RemoteBucketState> builder = Caffeine.newBuilder()
//                .removalListener((key, graph, cause) -> {});
//        proxyManager = new CaffeineProxyManager<>(builder, Duration.ofMinutes(10));
//    }
//
//    @Override
//    public boolean preHandle(@NonNull HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
//        if (handler instanceof HandlerMethod) {
//            HandlerMethod handlerMethod = (HandlerMethod) handler;
//            RateLimiter rateLimiter = handlerMethod.getMethodAnnotation(RateLimiter.class);;
//            if (rateLimiter != null) {
//                String key = "";
//                Bucket bucket = proxyManager.builder().build(key, () -> bucketConfigurationByRateLimiter(rateLimiter));
//                if (!bucket.tryConsume(1)) {
//                    response.setStatus(429);
//                    return false;
//                }
//            }
//        }
//        return true;
//    }
//
//    private BucketConfiguration bucketConfigurationByRateLimiter(RateLimiter rateLimiter) {
//        TimeUnit timeUnit = rateLimiter.unit();
//        long time = rateLimiter.time();
//        long limit = rateLimiter.limit();
//        Bandwidth bandwidth = Bandwidth.simple(limit, TimeUnit.SECONDS.equals(timeUnit) ? Duration.ofSeconds(time) : Duration.ofMinutes(time));
//        return BucketConfiguration.builder()
//        	.addLimit(bandwidth)
//       		.build();
//    }
//}